package com.mxf.code.service;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mxf.code.entity.SpaceEntity;
import com.mxf.code.mapper.SpaceMapper;
import com.mxf.code.response.LocationListResponse;
import com.mxf.code.response.LocationListWithTreeResponse;
import com.mxf.code.util.SpaceRedis;
import com.mxf.code.util.StreamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 空间位置管理
 *
 * @author mxf
 * @since 3.0 2022-11-09
 */
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, SpaceEntity> implements SpaceService {

    @Autowired
    private SpaceRedis spaceRedis;

    /**
     * 分隔符
     */
    public static final String SEPARATOR = "/";


    public boolean insertBatch(Collection<SpaceEntity> entityList) {
        return super.saveBatch(entityList);
    }

    @Override
    public String getAllLevelSpace(Long id) {
        SpaceServiceImpl gSpaceService = SpringUtil.getBean(SpaceServiceImpl.class);
        List<LocationListWithTreeResponse> tree = gSpaceService.locationListWithTree();
        return StreamUtil.findInTree(tree, rsp -> Objects.equals(rsp.getValue(), id), LocationListWithTreeResponse::getLabel, "/");
    }

    /**
     * 摆放位置树
     *
     * @return tree
     */
    @Override
    public List<LocationListWithTreeResponse> locationListWithTree() {
        List<LocationListWithTreeResponse> tree = spaceRedis.getLocationTreeList();
        if (Objects.isNull(tree)) {
            List<SpaceEntity> list = this.baseMapper.selectList(null);
            List<LocationListWithTreeResponse> rspList = StreamUtil.listToList(list, entity -> {
                LocationListWithTreeResponse rsp = new LocationListWithTreeResponse();
                rsp.setValue(entity.getId());
                rsp.setLabel(entity.getName());
                rsp.setParentId(entity.getParentSpaceId());
                return rsp;
            });
            tree = StreamUtil.listToTree(rspList,
                    e -> Objects.equals(e.getParentId(), 0L),
                    (parent, child) -> Objects.equals(parent.getValue(), child.getParentId())
            );
            spaceRedis.saveLocationTreeList(tree);
        }
        return tree;
    }

    @Override
    public Map<String, LocationListResponse> getAllLevelSpace() {
        Map<String, LocationListResponse> responses = spaceRedis.getLocationList();
        if (CollectionUtils.isEmpty(responses)) {
            responses = new HashMap<>();
            List<SpaceEntity> gSpaceEntities = this.baseMapper.selectList(null);
            Map<Long, List<SpaceEntity>> spaceListMap = StreamUtil.listToListMap(gSpaceEntities, SpaceEntity::getParentSpaceId);
            List<SpaceEntity> space0List = gSpaceEntities.stream().filter(gSpaceEntitie -> Long.valueOf("0")
                    .equals(gSpaceEntitie.getParentSpaceId())).collect(Collectors.toList());
            recursionAllLevelSpace(spaceListMap, space0List, responses);
            spaceRedis.saveLocationMap(responses);
        }
        return responses;
    }

    @Override
    public String getAllLevelSpaceById(Long id) {
        String allLevelSpaceById = spaceRedis.getAllLevelSpaceById(id);
        if (String.valueOf(id).equals(allLevelSpaceById)) {
            this.getAllLevelSpace();
            return spaceRedis.getAllLevelSpaceById(id);
        }
        return allLevelSpaceById;
    }

    /**
     * @param spaceListMap           根据parentId分组map
     * @param currentSpaceEntityList 当前层级接节点
     * @param responses              结果list
     * @author mxf
     * @description
     * @createTime 2023/2/6 14:55
     * @paramType [java.util.Map<java.lang.Long, java.util.List < com.mxf.code.entity.SpaceEntity>>, java.util.List<com.mxf.code.entity.SpaceEntity>, java.util.Map<java.lang.Long,com.mxf.code.response.LocationListResponse>]
     */
    private void recursionAllLevelSpace(Map<Long, List<SpaceEntity>> spaceListMap, List<SpaceEntity> currentSpaceEntityList,
                                        Map<String, LocationListResponse> responses) {
        if (CollectionUtils.isEmpty(currentSpaceEntityList)) {
            return;
        }
        List<SpaceEntity> tmpList = new ArrayList<>();
        currentSpaceEntityList.forEach(item -> {
            LocationListResponse locationListResponse = new LocationListResponse();
            locationListResponse.setValue(item.getId());
            locationListResponse.setLabel(item.getName());
            locationListResponse.setParentId(item.getParentSpaceId());
            responses.put(item.getId().toString(), locationListResponse);
            List<SpaceEntity> gSpaceEntities = spaceListMap.get(item.getId());
            if (!CollectionUtils.isEmpty(gSpaceEntities)) {
                for (SpaceEntity childSpace : gSpaceEntities) {
                    childSpace.setName(item.getName() + SEPARATOR + childSpace.getName());
                    tmpList.add(childSpace);
                }
            }
            spaceListMap.remove(item.getId());
        });
        recursionAllLevelSpace(spaceListMap, tmpList, responses);
    }

    @Override
    public boolean save(SpaceEntity entity) {
        return super.save(entity);
    }
}
